// 支付功能测试脚本
// 使用方法: node test-payment.js

require('dotenv').config();
const axios = require('axios');

const BASE_URL = 'http://localhost:5000';

async function testPayment() {
  console.log('🧪 开始测试支付宝支付功能...\n');

  // 1. 测试配置
  console.log('1️⃣ 检查支付配置...');
  const payment = require('./utils/payment');
  console.log('   ✅ AppID:', payment.ALIPAY_CONFIG.appId || '❌ 未配置');
  console.log('   ✅ 私钥:', payment.ALIPAY_CONFIG.privateKey ? '已配置' : '❌ 未配置');
  console.log('   ✅ 回调地址:', payment.ALIPAY_CONFIG.notifyUrl);
  console.log('   ✅ 沙箱模式:', payment.ALIPAY_CONFIG.isSandbox ? '已启用' : '❌ 未启用');
  console.log('   ✅ 网关地址:', payment.ALIPAY_CONFIG.gateway);
  console.log('');

  // 2. 测试后端服务
  console.log('2️⃣ 测试后端服务连接...');
  try {
    const balanceRes = await axios.get(`${BASE_URL}/api/payments/balance/1`);
    console.log('   ✅ 后端服务正常:', balanceRes.data);
  } catch (error) {
    console.log('   ❌ 后端服务连接失败:', error.message);
    return;
  }
  console.log('');

  // 3. 测试支付订单创建（需要提供实际的订单ID和用户ID）
  console.log('3️⃣ 测试支付订单创建...');
  console.log('   ⚠️  请提供以下信息进行完整测试:');
  console.log('   - 订单ID (订单状态必须是7=已送达)');
  console.log('   - 用户ID');
  console.log('   - 订单金额');
  console.log('');
  console.log('   📝 测试API调用示例:');
  console.log(`   POST ${BASE_URL}/api/payments/create`);
  console.log('   {');
  console.log('     "order_id": 订单ID,');
  console.log('     "user_id": 用户ID,');
  console.log('     "amount": 订单金额,');
  console.log('     "payment_method": "alipay"');
  console.log('   }');
  console.log('');

  // 4. 检查natapp
  console.log('4️⃣ 检查natapp连接...');
  try {
    const natappUrl = payment.ALIPAY_CONFIG.notifyUrl.replace('/api/payments/alipay/notify', '');
    const natappRes = await axios.get(natappUrl, { timeout: 5000 });
    console.log('   ✅ natapp连接正常');
  } catch (error) {
    if (error.code === 'ECONNREFUSED' || error.code === 'ETIMEDOUT') {
      console.log('   ⚠️  natapp可能未运行，请确认以下地址可访问:');
      console.log(`      ${payment.ALIPAY_CONFIG.notifyUrl.replace('/api/payments/alipay/notify', '')}`);
    } else {
      console.log('   ✅ natapp连接检查完成');
    }
  }
  console.log('');

  console.log('📋 下一步操作:');
  console.log('   1. 确保有一个状态为"已送达"(status=7)的订单');
  console.log('   2. 访问前端支付页面或使用以下curl命令测试:');
  console.log('');
  console.log('   curl -X POST http://localhost:5000/api/payments/create \\');
  console.log('     -H "Content-Type: application/json" \\');
  console.log('     -d \'{');
  console.log('       "order_id": 1,');
  console.log('       "user_id": 1,');
  console.log('       "amount": 10.00,');
  console.log('       "payment_method": "alipay"');
  console.log('     }\'');
  console.log('');
  console.log('   3. 支付成功后，检查后端日志中的回调信息');
}

testPayment().catch(console.error);

